<template>
	<view class="imageronghe">
		
		
		<view class="imagerongheBg">
			
			<!-- <text v-if="price" class="t_price"><image class='t_price_icon' src="/static/img/tip.png"></image>{{price}}</text> -->
			<text v-if="price"  class="t_price"><image class='t_price_icon' src="/static/img/tip.png"></image>免费使用（带水印）会员不限次数使用(无水印)</text>
			<view class="top" @click="onAddImgClick(1)">
				<view class="top_mid" v-if="muban_url">
					<image :src="muban_url" mode="aspectFit" class="imuban"></image>
				</view>
				<view class="top_mid" v-else style="height: 657rpx;">
					<uni-icons class="ii"  color="#9d9d9d" type="plusempty" size="30"></uni-icons>
					<text class="tt">上传模板图片(支持多脸)</text>
				</view>
				<view class="top_fuceng" v-if="muban_face_image_list && muban_face_image_list.length >1">
					<image class="imuban"  :src="muban_face_image_list[index].face_image_url"
						:class="{ active: select_muban_Index == index }" v-for="(item, index) in muban_face_image_list"
						:key="index" @click.stop="select_muban_Index = index"></image>

				</view>
			</view>
			<view class="middle">
				<view class="middle_1" :class="{ active: select_target_Index == index }" v-if="target_url"
					v-for="(item, index) in target_face_image_list" :key="index" @click="handleSelectAvater(index)">
					<image class="itarget" :src="target_face_image_list[index].face_image_url" mode="aspectFit"></image>
				</view>				
				<view class="middle_1 middle_uoplaod_icon" @click="pop_show=true">
				<!-- 	<image src="/static/img/pub_add.png" class="ii"></image> -->
				</view>
				<!-- <text class="tt" v-if="!target_url">请提供面部完全正对镜头的清晰照片，越是轮廓分明， \n 换脸效果越好（非常重要）</text> -->
				<text class="tt" v-if="!target_url">请提供正面拍摄且高清晰度的照片，面部需完整无遮挡。 照片轮廓越分明, 换脸融合效果越自然（非常重要）</text>
			</view>
			<view class="bottom">
			<view class="item">
				<view class="item_1" @click="onTongdaoTipClick">
					<text class="t1">换脸通道</text>
					<image class='t1_icon' src="/static/img/tip.png"></image>
				</view>
				<radio-group class="radioGroup" @change="changeTongdao" style="margin-right: 20rpx;">
					<label>
						<radio value="1" checked="true" class="ro" /><text class="tt">通道1</text>
					</label>
					<label>
						<radio value="2" class="ro" /><text class="tt">通道2</text>
					</label>
					<label>
						<radio value="3" class="ro" /><text class="tt">通道3</text>
					</label>
					<label>
						<radio value="4" class="ro" /><text class="tt">通道4</text>
					</label>
					<label>
						<radio value="5" class="ro" /><text class="tt ttPro" style="color: #7E8BFF;font-weight:400;">通道5</text>
					</label>

				</radio-group>
				
				
			</view>
		</view>
		<button class="btn" @click="startBianLian" :loading="loadding" :disabled="loadding">开始换脸</button>
		</view>

		
		<view class="tip">
			<text class="t1">温馨提示<text>*</text></text>
			<text class="t2">
				1、模板图，被融合人脸边缘与图片边缘需保留一定间距，确保人脸核心区域完整处于图片内。
				2、人脸图，需选用正脸且清晰的图片。
				3、换脸通道为可选项，不同通道呈现的换脸效果存在差异。
				4、您在使用本服务期间，必须严格遵守相关法律法规以及本平台的服务协议，严禁将本服务用于非法用途，不得借助本服务实施违反法律法规或侵犯他人合法权益的行为。
				您需保证自身或应用用户上传、使用、发布的照片、素材等信息内容，已获得相关权利人的合法授权，不存在侵犯他人肖像权、版权等合法权益的情况，也不违反相关法律法规、政策规定以及公序良俗。
				您需对应用中用户使用本服务所产生的内容负责，确保其符合法律法规、政策规定和公序良俗。若违反上述要求引发任何纠纷，均由您自行承担责任，与本平台无关。本平台有权立即终止您在本平台的所有服务，并保留追究您法律责任的权利。
			</text>
		</view>
		<imgPop :show="pop_show" @handleClose="pop_show=false" @getUploadImg="onAddImgClick(2)"></imgPop>
		
	</view>
</template>

<script>
	import imgPop from './cmp/imgPop.vue';
	import {
		imageronghe
	} from '@/src/api/huanlian.js';
	import {
		getAbilityPrice,
		getUser
	} from '@/src/utils/utils.js';
	import {
		upload_file
	} from '@/src/utils/uni-fetch.js';

	export default {
		components: {
			imgPop,
		},
		data() {
			return {
				muban_id: null,
				muban_url: null,
				muban_face_image_list: [],
				select_muban_Index: null,

				target_id: null,
				target_url: null,
				target_face_image_list: [],
				select_target_Index: null,

				loadding: false,
				price: null,
				tongdao: 1,
				pop_show:false
			};
		},
		onLoad({
			muban_id,
			muban_url,
			face_image_list
		}) {
			this.muban_id = muban_id;
			this.muban_url = muban_url;
			if (face_image_list) {
				this.muban_face_image_list = JSON.parse(decodeURIComponent(face_image_list))
				if (this.muban_face_image_list && this.muban_face_image_list.length > 1) {
					this.select_muban_Index = 0
				}
			}
			this.init_price();

		},
		methods: {
			onTongdaoTipClick() {
				uni.showModal({
					title: '通道介绍',
					content: '每种通道来自不同公司的换脸算法，所以结果效果也各不相同，可以自己体验不同效果',
					showCancel: false
				})
			},
			changeTongdao(v) {
				this.tongdao = v.detail.value
				if (this.tongdao == 1) {
					this.price = this.price1
					uni.showModal({
						title: '通道一',
						content: `${this.price}\r\n支持2000*2000px，如果图片大于该尺寸将会压缩至该尺寸`,
						showCancel: false
					})
				} else if (this.tongdao == 2) {
					this.price = this.price2
					uni.showModal({
						title: '通道二',
						content: `${this.price}\r\n支持1920*1080px，如果图片大于该尺寸将会压缩至该尺寸`,
						showCancel: false
					})
				} else if (this.tongdao == 3) {
					this.price = this.price2
					uni.showModal({
						title: '通道三',
						content: `${this.price}\r\n支持4096*4096px，如果图片大于该尺寸将会压缩至该尺寸`,
						showCancel: false
					})
				} else if (this.tongdao == 4) {
					this.price = this.price2
					uni.showModal({
						title: '写真定制版',
						content: `${this.price}\r\n不支持多人及选脸融合\r\n支持4096*4096px，如果图片大于该尺寸将会压缩至该尺寸`,
						showCancel: false
					})
					if (this.muban_face_image_list && this.muban_face_image_list.length > 1) {
						this.muban_id = null
						this.muban_url = null
						this.select_muban_Index = null;
						this.muban_face_image_list = null
					}
					if (this.target_face_image_list && this.target_face_image_list.length > 1) {
						this.target_id = null
						this.target_url = null
						this.select_target_Index = null;
						this.target_face_image_list = null
					}

				} else if (this.tongdao == 5) {
					this.price = this.price3
					uni.showModal({
						title: '专业版',
						content: `${this.price}\r\n支持8000*8000px，如果图片大于该尺寸将会压缩至该尺寸`,
						showCancel: false
					})
				}
			},
			handleSelectAvater(i) {
				this.select_target_Index = i;
			},
			async init_price() {
				try {
					this.price1 = await getAbilityPrice('ImageRongHe');
					this.price2 = await getAbilityPrice('ImageRongHe2');
					this.price3 = await getAbilityPrice('ImageRongHe3');
					this.price = this.price1
				} catch (e) {
					console.log(e);
				}
			},
			async onAddImgClick(type) {
				// if (type == 1 && this.muban_id && typeof this.muban_id != 'number') return;
				// const [error, res] = await uni.chooseImage({
				// 	count: 1,
				// 	sizeType: ['compressed', 'original'],
				// 	sourceType: ['album', 'camera'] //从相册选择
				// });
				// if (error) {
				// 	console.error(error)
				// 	if (error.errCode == -2 || error.errCode == 0 || error.errMsg == "chooseImage:fail cancel") return;
				// 	uni.showModal({
				// 		title: '选取图片失败',
				// 		content: error.errMsg,
				// 		showCancel: false
				// 	});
				// 	return;
				// }
				
				// try {
				//   const { tempFilePaths, tempFiles, errMsg } = await uni.chooseImage({
				//     count: 1,
				//     sizeType: ['compressed', 'original'],
				//     sourceType: ['album', 'camera']
				//   });
				  
				//   if(errMsg !== 'chooseImage:ok') {
				//     throw new Error(errMsg)
				//   }
				  
				// } catch (error) {
				//  uni.showModal({
				//  	title: '选取图片失败',
				//  	content: error.errMsg,
				//  	showCancel: false
				//  });
				//  return;
				// }


				try {
					const { tempFilePaths, tempFiles, errMsg } = await uni.chooseImage({
					  count: 1,
					  sizeType: ['compressed', 'original'],
					  sourceType: ['album', 'camera'],					  
					});
										
					if(errMsg !== 'chooseImage:ok') {
					  //throw new Error(errMsg)
					  	uni.showModal({
					  		title: '选取图片失败',
					  		content: errMsg,
					  		showCancel: false
					  	});
					}
										
					let result = await upload_file({
						url: '/huanlian/up_image/',
						file: {
							name: 'image',
							uri: tempFilePaths[0]
						},
						formData: {
							img_type: type,
							ability: 'ImageRongHe'
						}
					}, true, false);

					if (!result.data.face_image_list || result.data.face_image_list.length == 0) {
						uni.showModal({
							showCancel: false,
							content: '您上传的图片中没有人脸，请重新上传'
						});
						if (type == 1) {
							this.muban_id = null
							this.muban_url = null
							this.select_muban_Index = null;
							this.muban_face_image_list = []
						} else {
							this.target_id = null
							this.target_url = null
							this.select_target_Index = null;
							this.target_face_image_list = []
						}
						return;
					}
					if (this.tongdao == 4 && result.data.face_image_list && result.data.face_image_list.length > 1) {
						uni.showModal({
							content: '该通道为写真定制版，只支持单人脸图片',
							showCancel: false
						});
						return;
					}
					if (type == 1) {
						this.muban_id = result.data.id;
						this.muban_url =tempFilePaths[0];
						this.muban_face_image_list = result.data.face_image_list;
						this.select_muban_Index = 0;
					} else {
						this.target_face_image_list = result.data.face_image_list;
						this.target_id = result.data.id;
						this.target_url = tempFilePaths[0];
						if (this.target_face_image_list.length == 1) {
							this.select_target_Index = 0;
						} else {
							this.select_target_Index = null;
						}
					}
				} catch (e) {
					if (!e) return
					console.error(e);
					uni.showModal({
						title: '上传图片失败',
						//content: e.errMsg,
						content:'上传图片失败',
						showCancel: false,
					});
				}
			},
			async startBianLian() {
				let _this = this;
				if (!this.muban_id) {
					_this.$showToast('请选择模板图');
					return;
				}
				if (this.select_target_Index == null) {
					_this.$showToast('请上传人脸图，并且选择人脸');
					return;
				}

				try {
					this.loadding = true
					let select_muban_face_info = ''
					if (this.select_muban_Index != null && this.muban_face_image_list.length > 0) {
						select_muban_face_info = JSON.stringify(this.muban_face_image_list[this
							.select_muban_Index].face_rect)
					}
					
					console.log(select_muban_face_info)
					let result = await imageronghe({
						tongdao: this.tongdao,
						template_id: this.muban_id,
						target_id: this.target_id,
						select_target_face_info: JSON.stringify(this.target_face_image_list[this
							.select_target_Index].face_rect),
						select_muban_face_info: select_muban_face_info
					});
					getUser({}, true);
					uni.hideLoading();
					uni.navigateTo({
						url: `/src/pages/Ability/Result/Result?result_img=${encodeURIComponent(result.data.image_url)}&tip=${result.data.tip}`
					});
				} catch (e) {
					if (!e) return
					console.log(e.errMsg || e.message)
					uni.showModal({
						content: e.errMsg || e.message,
						showCancel: false
					});
				} finally {
					this.loadding = false
				}
			}
		}
	};
</script>

<style lang="scss">
	@import 'ImageRongHe.scss';
</style>